package com.sxygsj.baselibrary.network.netUtils

import android.net.Uri
import com.sxygsj.baselibrary.network.DownloadWork
import com.sxygsj.baselibrary.application.BaseApplication
import com.sxygsj.baselibrary.network.netInterface.ProgressInterface

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import okio.Okio
import java.io.File

/**
 * @Author LD
 * @Time 2021/3/3 10:04
 * @Describe 下载文件工具类
 * @Modify
 */
object DownloadUtil {


    private var job = Job()

    /**
     * 下载文件
     * fileAddress：下载地址
     * filePath:保存的路径
     */
    fun downloadFile(fileAddress: String, filePath: String?,fileName:String?,progressInterface: ProgressInterface) {
        val scope = CoroutineScope(job)
        scope.launch {

            try {
                var responseBody = DownloadWork.downloadFile(fileAddress)

                var mFilePath=""
                var mFileName=""
                //文件路径为空
                mFilePath = if(filePath.isNullOrEmpty()){
                    BaseApplication.context.getExternalFilesDir(null)?.absolutePath.toString()
                }else{
                    //TODO: 2021/3/3 日后可加判断文件夹是否存在，并根据其创建文件夹
                    filePath
                }

                //包含后缀的文件名
                var segmentName = Uri.parse(fileAddress).lastPathSegment
                //文件名为空
                mFileName = if(fileName.isNullOrEmpty()){
                    //没设名字，也获取不到，则用时间戳来设置文件名
                    segmentName ?: "${System.currentTimeMillis()}"+"."+responseBody.contentType()?.type()
                }else{
                    //文件名不为空
                    if(segmentName==null){
                        fileName+"."+responseBody.contentType()?.type()
                    }else{

                        fileName+ segmentName.substring(Uri.parse(fileAddress).lastPathSegment!!.lastIndexOf("."))
                    }
                }
                var pathname =  "$mFilePath/$mFileName"
                var file = File(pathname)

                //通过流的方式写文件
                //总长度
                var contentLength = responseBody.contentLength()

                //生产临时存储的buffer
                var bufferedSink = Okio.buffer(Okio.sink(file))
                var buffer = bufferedSink.buffer()

                var source = responseBody.source()

                //一次读取1024kb
                var bufferSize: Long = 1024   //200kb
                //实际一次读取的大小
                var len: Int = 0
                //显示进度
                var currentLength: Long = 0

                while (source.read(buffer, bufferSize).toInt().also { len = it } != -1) {
                    bufferedSink.emit()
                    currentLength += len
                    progressInterface.onProgress((100 * currentLength / contentLength).toInt())
                }
                bufferedSink.close()
                //写这个会报close错误
//                source.close()
                progressInterface.onSuccess(responseBody)

                //下载完成
            } catch (e: Exception) {
                progressInterface.onFailed(e.message.toString())
            }
        }
    }

    /**
     * 传下载路径，不传文件名
     */
    fun downloadFileWithPath(fileAddress: String, filePath: String,progressInterface: ProgressInterface){
        downloadFile(
            fileAddress,
            filePath,
            null, progressInterface
        )
    }

    /**
     * 不传下载路径，传文件名
     */
    fun downloadFile(fileAddress: String, fileName:String,progressInterface: ProgressInterface){
        downloadFile(
            fileAddress,
            null,
            fileName, progressInterface
        )
    }
    /**
     * 不传下载路径，不传文件名
     */
    fun downloadFile(fileAddress: String,progressInterface: ProgressInterface){
        downloadFile(
            fileAddress,
            null,
            null, progressInterface
        )
    }

}